<template>
  <div class="mod-shop-notice">
    <div class="search-bar">
      <el-form :inline="true" class="search-form" ref="searchForm" :model="searchForm" size="small">
        <div class="input-row">
          <el-form-item prop="title" label="登记名称:" class="search-form-item">
            <el-input type="text" v-model="searchForm.registeredName" placeholder="登记名称"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="default-btn primary-btn" @click="searchChange(true)">{{ $t('product.search') }}</div>
            <div class="default-btn" @click="resetSearchForm('searchForm')">{{ $t('product.reset') }}</div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          class="default-btn primary-btn"
          @click="addOrUpdateHandle()">
          {{ $t('sysManagement.add') }}
        </div>
      </div>
      <div class="table-con notice-table">
        <el-table
          ref="noticeListTable"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%">
          <el-table-column
            fixed
            type="index"
            width="80"
            :label="$t('brand.serialNumber')">
          </el-table-column>

          <el-table-column
            fixed
            align="center"
            prop="registeredName"
            label="登记名称">
            <template slot-scope="scope">
              <span class="table-cell-text">{{ scope.row.registeredName }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed
            align="center"
            prop="information"
            label="数字资产信息">
            <template slot-scope="scope">
              <span class="table-cell-text">{{ scope.row.information }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed
            align="center"
            prop="possessor"
            label="持有人">
            <template slot-scope="scope">
              <span class="table-cell-text">{{ scope.row.possessor }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed
            align="center"
            prop="createTime"
            label="登记时间">
            <template slot-scope="scope">
              <span class="table-cell-text">{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="230"
          >
            <template slot-scope="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click.stop="deleteHandle(resourcesUrl + scope.row.qrCodeUrl)"
                >下载
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        v-if="dataList.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="refreshChange"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './certificate-add-or-update.vue'

export default {
  data () {
    return {
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      theData: null, // 保存上次点击查询的请求条件

      dataList: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      searchForm: {
        registeredName: ''
      },
      dataListLoading: false,
      addOrUpdateVisible: false
    }
  },
  components: {
    AddOrUpdate
  },
  created () {
    this.getDataList()
  },
  mounted () {
  },
  methods: {
    getDataList (page, newData = false) {
      if (this.page) {
        let size = Math.ceil(this.page.total / this.page.pageSize)
        this.page.currentPage = (this.page.currentPage > size ? size : this.page.currentPage) || 1
      }
      if (newData || !this.theData) {
        this.theData = JSON.parse(JSON.stringify(this.searchForm))
      }
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/platform/certificate/page'),
        method: 'get',
        params: this.$http.adornParams(Object.assign({
          current: page == null ? this.page.currentPage : page.currentPage,
          size: page == null ? this.page.pageSize : page.pageSize
        }, this.theData))
      }).then(({data}) => {
        this.dataList = data.records
        this.page.total = data.total
        this.dataListLoading = false
      })
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    /**
     * 通过URL下载图片
     * @param {string} url - 图片地址
     * @param {string} [fileName='download'] - 保存的文件名（无需扩展名）
     */
    deleteHandle (url, fileName = 'download') {
      // 1. 创建隐藏的临时元素
      const tempLink = document.createElement('a')
      tempLink.style.display = 'none'
      document.body.appendChild(tempLink)

      // 2. 创建图片对象
      const img = new Image()

      // 3. 处理跨域请求（需要服务器支持CORS）
      img.crossOrigin = 'Anonymous'

      // 4. 图片加载完成回调
      img.onload = () => {
        try {
          // 5. 创建Canvas处理图片
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')

          // 6. 设置Canvas尺寸（使用原始尺寸避免缩放失真）
          canvas.width = img.naturalWidth
          canvas.height = img.naturalHeight

          // 7. 绘制图片到Canvas
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

          // 8. 转换为Blob格式（兼容性处理）
          canvas.toBlob(blob => {
            // 9. 创建对象URL
            const objectUrl = URL.createObjectURL(blob)

            // 10. 设置下载属性
            tempLink.href = objectUrl
            tempLink.download = `${fileName}.png` // 强制使用png格式

            // 11. 触发下载（需要用户交互）
            tempLink.click()

            // 12. 清理内存
            URL.revokeObjectURL(objectUrl)
            canvas.remove()
          }, 'image/png')

        } catch (error) {
          console.error('图片处理失败:', error)
          this.showError('图片处理失败')
        } finally {
          // 13. 清理DOM元素
          document.body.removeChild(tempLink)
        }
      }

      // 14. 错误处理
      img.onerror = () => {
        console.error('图片加载失败:', url)
        this.showError('图片加载失败')
        document.body.removeChild(tempLink)
      }

      // 15. 开始加载图片
      img.src = url

      // 添加时间戳避免缓存问题
      if (url.indexOf('?') === -1) {
        img.src += '?t=' + Date.now()
      } else {
        img.src += '&t=' + Date.now()
      }
    },

// 错误提示函数
    showError (message) {
      const errorDiv = document.createElement('div')
      errorDiv.style = 'position:fixed;top:20px;right:20px;padding:15px;background:#ff4444;color:white;'
      errorDiv.textContent = message
      document.body.appendChild(errorDiv)

      setTimeout(() => {
        document.body.removeChild(errorDiv)
      }, 3000)
    },

    deleteHandle1 (url) {
      const link = document.createElement('a')
      link.style.display = 'none'
      document.body.appendChild(link)
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = document.querySelector('img')
      ctx.drawImage(url, 0, 0)

      const downloadBtn = document.createElement('button')
      downloadBtn.innerText = 'Download'
      downloadBtn.addEventListener('click', () => {
        const dataURL = canvas.toDataURL('image/png')
        link.href = dataURL
        link.download = 'image.png'
        link.click()
      })
      document.body.appendChild(downloadBtn)
    }
    ,
// 刷新回调用
    refreshChange () {
      this.getDataList(this.page)
    }
    ,
    searchChange (newData = false) {
      this.page.currentPage = 1
      this.getDataList(this.page, newData)
    }
    ,
    /**
     * 重置表单
     * @param {String} formName 表单名称
     */
    resetSearchForm (formName) {
      this.$refs[formName].resetFields()

      this.page.currentPage = 1
      this.getDataList(this.page, true) //重置表单加载初始列表
    }
    ,

    handleSizeChange (val) {
      this.page.pageSize = val
      this.getDataList()
    }
    ,
    handleCurrentChange (val) {
      this.page.currentPage = val
      this.getDataList()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
